package com.example.home.fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.example.home.activity.R;
import com.example.home.adapter.ClassifyAdapter;
import com.example.home.api.ApiService;
import com.example.home.interfaces.ResponseCallback;
import com.example.home.viewmodel.ResponseData;
import com.example.home.viewmodel.classify.CategoryList;
import com.example.home.viewmodel.classify.ClassifyData;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ClassifyFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ClassifyFragment extends Fragment {

    private long lastClickTime = 0;

    private ListView classifyLeft;

    private List<CategoryList> categoryList;

    private ClassifyAdapter categoryAdapter;


    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    public ClassifyFragment() {
        // Required empty public constructor
    }

    private void initView(View view){
        classifyLeft = view.findViewById(R.id.classify_left);
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ClassifyFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ClassifyFragment newInstance(String param1, String param2) {
        ClassifyFragment fragment = new ClassifyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_classify, container, false);
        initView(view);

        ApiService.GetClassify(new ResponseCallback<ResponseData<ClassifyData>>() {
            @Override
            public void onSuccess(ResponseData<ClassifyData> result) {
                // 1. 多层判空
                if (result == null || result.getData() == null || result.getData().getCategoryList() == null) {
                    Log.e("ClassifyFragment", "Data is null!");
                    return;
                }

                // 2. 更新数据前检查Fragment是否已销毁
                if (getActivity() == null || isDetached()) {
                    return;
                }
                categoryList = result.getData().getCategoryList();
                categoryAdapter = new ClassifyAdapter(view.getContext(),categoryList);
                Log.e("TAG", categoryList.toString() );
                classifyLeft.setAdapter(categoryAdapter);
                classifyLeft.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        //增加防抖机制,5s内只允许点击一次
                        if (System.currentTimeMillis() - lastClickTime < 1000) {
                            return;
                        }
                        lastClickTime = System.currentTimeMillis();
                        selectItem(position);
                    }
                });
                if (!categoryList.isEmpty()) {
                    selectItem(0);
                }
            }
        });
//        selectItem(0);
        return view;
    }

    public void selectItem(int index){
        // 1. 检查Fragment是否活跃
        if (!isAdded() || getActivity() == null) {
            return;
        }

        // 2. 检查数据有效性
        if (categoryList == null || index < 0 || index >= categoryList.size()) {
            return;
        }

        // 3. 更新选中状态
        for (CategoryList item : categoryList) {
            item.setChecked(false);
        }
        categoryList.get(index).setChecked(true);

        // 4. 切换Fragment（检查父容器是否存在）
        if (getView() == null || getView().findViewById(R.id.classify_right) == null) {
            return;
        }

        FragmentTransaction ft = getParentFragmentManager().beginTransaction();
        ClassifyContentFragment ccf = ClassifyContentFragment.newInstance(
                String.valueOf(categoryList.get(index).getId()), ""
        );
        ft.replace(R.id.classify_right, ccf);
        ft.commitAllowingStateLoss();

        // 5. 通知Adapter更新（检查Adapter是否存在）
        if (categoryAdapter != null) {
            categoryAdapter.notifyDataSetChanged();
        }
    }
}